package com.jiumi.baseconfig.controller;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import javax.management.remote.rmi._RMIConnection_Stub;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.jiumi.common.annotation.DataScope;
import com.jiumi.common.constant.UserConstants;
import com.jiumi.common.core.domain.entity.SysUser;
import com.jiumi.common.utils.PageUtils;
import com.jiumi.common.utils.SecurityUtils;
import com.jiumi.common.utils.StringUtils;
import com.jiumi.system.service.ISysConfigService;
import com.jiumi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.jiumi.common.annotation.Log;
import com.jiumi.common.core.controller.BaseController;
import com.jiumi.common.core.domain.AjaxResult;
import com.jiumi.common.enums.BusinessType;
import com.jiumi.baseconfig.domain.BaseUser;
import com.jiumi.baseconfig.service.IBaseUserService;
import com.jiumi.common.utils.poi.ExcelUtil;
import com.jiumi.common.core.page.TableDataInfo;

/**
 * 用户信息Controller
 *
 * @author jiumi
 * @date 2023-05-21
 */
@RestController
@RequestMapping("/baseconfig/userinfo")
public class BaseUserController extends BaseController {
    @Autowired
    private IBaseUserService baseUserService;

    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:list')")
    @GetMapping("/list")
    @DataScope(userAlias = "u")
    public TableDataInfo list(BaseUser baseUser) {
        startPage();
        List<BaseUser> list = baseUserService.selectBaseUserList(baseUser);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BaseUser baseUser) {
        List<BaseUser> list = baseUserService.selectBaseUserList(baseUser);
        ExcelUtil<BaseUser> util = new ExcelUtil<BaseUser>(BaseUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(baseUserService.selectBaseUserByUserId(userId));
    }

    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody BaseUser baseUser) {

        if(UserConstants.NOT_UNIQUE.equals(baseUserService.checkAuthName(baseUser))){
            return AjaxResult.error("新增用户"+baseUser.getAuthName()+"失败，用户已存在");
        }

        //判断手机号是否存在
        if(StringUtils.isNotEmpty(baseUser.getPhonenumber())) {
            BaseUser baseUsers = baseUserService.selectBaseUserByUserPhone(baseUser.getPhonenumber());
            if (baseUsers != null) {
                return AjaxResult.error("手机号已存在");
            }
        }
        //生成密码
        if (StringUtils.isNotEmpty(baseUser.getPassword())) {
            String encryPwd = SecurityUtils.encryptPassword(baseUser.getPassword());
            baseUser.setPassword(encryPwd);
        }
        Long promoterId = baseUser.getPromoterId();
        Long recipientId = baseUser.getRecipientId();
        if (StringUtils.isNotNull(promoterId)) {

            SysUser proUser = sysUserService.selectUserById(promoterId);
            baseUser.setPromoterName(proUser.getUserName()+proUser.getNickName());
        } else {
            baseUser.setPromoterName("");
        }
        if (StringUtils.isNotNull(recipientId)) {
            SysUser rec = sysUserService.selectUserById(recipientId);
            baseUser.setRecipientName(rec.getUserName()+rec.getNickName());
        } else {
            baseUser.setRecipientName("");
        }
        baseUser.setCreateBy(String.valueOf(getUserId()));
        baseUser.setAddType("2");
        int i = baseUserService.insertBaseUser(baseUser);
        return toAjax(i);
    }

    @GetMapping("/getUserName")
    public AjaxResult genUserName() {
        BaseUser user = new BaseUser();
        String userPrefix = Optional.ofNullable(sysConfigService.selectConfigByKey("user_prefix")).orElse("HX");
        Long idx = 5169L;
        String newUserName ="";
        try{
            long memberNo = baseUserService.selectUserNameMaxNo();
            newUserName = userPrefix + (memberNo + 1);
        }
        catch (Exception e){
           Long count = baseUserService.selectUserNameNotEmptyCount();
            newUserName = userPrefix + (idx+count + 1);
        }



        Map<String, String> data = new HashMap<>();
        data.put("userName", newUserName);
        String pwd = String.valueOf(new Random().nextInt(900000) + 100000);
        data.put("password", pwd);

        return AjaxResult.success("生成成功", data);
    }

    @GetMapping("/getManageUserName")
    public AjaxResult getManageUserName() {
        BaseUser user = new BaseUser();
        String userPrefix = Optional.ofNullable(sysConfigService.selectConfigByKey("user_prefix")).orElse("HX");
        long count=0;
        String newUserName ="";
        try{
            long memberNo = baseUserService.selectUserNameMaxNo();
            long userNo = sysUserService.selectUserNameMaxNo();
            if(memberNo>userNo){
                count=memberNo;
            }else{
                count=userNo;
            }
            newUserName = userPrefix + ( count + 1);
        }
        catch (Exception e){
            Long idx = 5169L;
            count = baseUserService.selectUserNameNotEmptyCount();
            newUserName = userPrefix + (idx + count + 1);
        }

        Map<String, String> data = new HashMap<>();
        data.put("userName", newUserName);
        return AjaxResult.success("生成成功", data);
    }


    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BaseUser user) {

        if(UserConstants.NOT_UNIQUE.equals(baseUserService.checkAuthName(user))){
            return AjaxResult.error("新增用户"+user.getAuthName()+"失败，用户已存在");
        }

        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(baseUserService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }



          if (StringUtils.isNotEmpty(user.getPassword()) ) {
              String s = SecurityUtils.encryptPassword(user.getPassword());
              user.setPassword(s);
        }



        Long promoterId = user.getPromoterId();
        Long recipientId = user.getRecipientId();
        if (StringUtils.isNotNull(promoterId)) {

            SysUser proUser = sysUserService.selectUserById(promoterId);
            user.setPromoterName(proUser.getUserName()+proUser.getNickName());
        } else {
            user.setPromoterName("");
        }
        if (StringUtils.isNotNull(recipientId)) {
            SysUser rec = sysUserService.selectUserById(recipientId);
            user.setRecipientName(rec.getUserName()+rec.getNickName());
        } else {
            user.setRecipientName("");
        }
        user.setUpdateBy(getUsername());
        return toAjax(baseUserService.updateBaseUser(user));
    }

    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:edit')")
    @Log(title = "添加会员", businessType = BusinessType.UPDATE)
    @PostMapping("/addMember")
    public AjaxResult addMember(@RequestBody BaseUser user) {
        Long userId = user.getUserId();
        BaseUser baseUser = baseUserService.selectBaseUserByUserId(userId);
        if("Y".equals(baseUser.getIsMember())){
            return AjaxResult.error("该用户已转化为会员状态");
        }
        if(UserConstants.NOT_UNIQUE.equals(baseUserService.checkAuthName(baseUser))){
            return AjaxResult.error("新增会员"+baseUser.getAuthName()+"失败，用户已存在");
        }

        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(baseUserService.checkPhoneUnique(user))) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }


        if (StringUtils.isEmpty(user.getUserName())) {
            return AjaxResult.error("账号不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            return AjaxResult.error("密码不能为空");
        }

        String s = SecurityUtils.encryptPassword(user.getPassword());
        user.setPassword(s);
        user.setIsMember("Y");
        user.setUpdateBy(getUsername());
        return toAjax(baseUserService.updateBaseUser(user));
    }

    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping("/addMemberUser")
    public AjaxResult addMemberUser(@RequestBody BaseUser user) {
        if(UserConstants.NOT_UNIQUE.equals(baseUserService.checkAuthName(user))){
            return AjaxResult.error("新增会员"+user.getAuthName()+"失败，用户已存在");
        }

        //判断手机号是否存在
        if(StringUtils.isNotEmpty(user.getPhonenumber())){
            BaseUser bu = new BaseUser();
            bu.setPhonenumber(user.getPhonenumber());
            List<BaseUser> baseUsers = baseUserService.selectBaseUserList(bu);
            if (baseUsers.size() > 0) {
                return AjaxResult.error("手机号已存在");
            }
        }
        Long promoterId = user.getPromoterId();
        Long recipientId = user.getRecipientId();
        if (StringUtils.isNotNull(promoterId)) {

            SysUser proUser = sysUserService.selectUserById(promoterId);
            user.setPromoterName(proUser.getUserName()+proUser.getNickName());
        } else {
            user.setPromoterName("");
        }
        if (StringUtils.isNotNull(recipientId)) {
            SysUser rec = sysUserService.selectUserById(recipientId);
            user.setRecipientName(rec.getUserName()+rec.getNickName());
        } else {
            user.setRecipientName("");
        }
        if (StringUtils.isEmpty(user.getUserName())) {
            return AjaxResult.error("账号不能为空");
        }
        if (StringUtils.isEmpty(user.getPassword())) {
            return AjaxResult.error("密码不能为空");
        }

        String s = SecurityUtils.encryptPassword(user.getPassword());
        user.setPassword(s);
        user.setIsMember("Y");
        user.setUpdateBy(getUsername());
        user.setCreateBy(String.valueOf(getUserId()));
        user.setAddType("1");
        return toAjax(baseUserService.insertBaseUser(user));
    }

    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPermi('baseconfig:userinfo:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(baseUserService.deleteBaseUserByUserIds(userIds));
    }
}
